﻿var productURL = '/api/productApi';
jQuery.support.cors = true;
var dataModified = false;
var productList=[];

$(document).ready(function () {
    /*Event Binding*/
    /*From Masteg page*/
    $('#ProductMenu').on("click", function () { ListAllProducts(); });

    /*List Page*/
    $('#Content').on("click", 'a.EditProduct', function (evt) { EditProduct(evt.target); });
    $('#Content').on("click", 'a.DeleteProduct', function (evt) { DeleteProduct(evt.target); });

    /*Edit Page*/
    $('#Content').on("click", 'input.SaveProduct', function (evt) { SaveProduct(evt.target); });
    $('#Content').on("click", 'input.ListAllProducts', function () { ListAllProducts(); });

    dataModified = true;        //For first time load
});

function ListAllProducts() {
    $('#Content').fadeIn(1000);
    $('#Content').html('Laoding Product..');
    if (dataModified) {
        $.getJSON(productURL, function (products) {
            productList = products;
            RenderProductGrid();
            dataModified = false;
        }).fail(function (jqxhr, textStatus, error) {
            alert(error);
        });
    }
    else { RenderProductGrid(); }
}

function RenderProductGrid() {
    $('#Content').html('');
    $('<Table id="Grid" ><tr class="header"><th width="40%">Product</th><th width="30%">Category</th><th width="15%">Price</th><th colspan="2" width="15%"></th></tr></Table>').appendTo('#Content');
    if (productList.length > 0) {
        $.each(productList, function (i, prod) {
            $('<tr ProdId=' + prod.ProductId + '><td ><a href="#" class="EditProduct">' + prod.ProductName +
              '</a></td><td>' + prod.CategoryName + '</td><td class="Money">$&nbsp;' + prod.Price +
              '</td><td><a href="#" class="EditProduct">Edit</a>' +
              '</td><td><a href="#" class="DeleteProduct">Delete</a>' +
              '</td></tr>').appendTo('#Grid').fadeIn();
        });
    }
    //$('<tr ProdId=0><td></td><td colspan="4"><input type="button" value="Add Product" id="EditProduct"  /></td></tr>').appendTo('#Grid');
}

function EditProduct(obj) {
    $('#Content').html('Laoding Product..');
    $.getJSON(productURL + '/' + $(obj).closest('tr').attr('ProdId'), function (product) {
        $('#Content').html('').fadeIn();
        $('<form action="/"><input type="hidden" name="ProductId" value="' + product.ProductId + '" />' +
            '<input type="hidden" name="CategoryId" value="' + product.CategoryId + '" />' +
            '<table><tr><td>Product Name</td>' +
            '<td><input type"text" name="ProductName" value="' + product.ProductName + '" /></td></tr>' +
            '<tr><td>Category</td>' +
            '<td><input type"text" name="CategoryName" readonly=readonly value="' + product.CategoryName + '" /></td></tr>' +
            '<tr><td>Price</td>' +
            '<td><input type"text" name="Price" value="' + product.Price + '" /></td></tr>' +
            '<tr><td colspan="2" align="right"><input type="button" class="SaveProduct" value="Save" />&nbsp;' +
            '<input type="button" class="ListAllProducts" value="Cancel" /></td></tr><table></form>'
            ).appendTo('#Content').fadeIn();
    });
}
function DeleteProduct(obj) {
    var row = $(obj).closest('tr');
    row.addClass('highlight');
    if (confirm('Are you sure!, Do you want to delete this Item?')) {
        $.ajax({
            type: 'DELETE',
            url: productURL + '/' + row.attr('ProdId'),
            success: function () {
                $(obj).closest('tr').fadeOut();
            }
        });
    } else {
        row.removeClass('highlight');
    }
}
function SaveSuccess() {

    ShowStatus('Product Saved...');
    $('#Content').fadeOut(1000);
    dataModified = true;
    setTimeout(ListAllProducts, 1000)
}

function collectFormData(fields) {
    var data = {};
    for (var i = 0; i < fields.length; i++) {
        var $item = $(fields[i]);
        data[$item.attr('name')] = $item.val();
    }
    return data;
}

function SaveProduct(obj) {
    var form = $(obj).closest('form');
    var $inputs = form.find('[name]');
    var data = collectFormData($inputs);
    $.ajax({
        type: 'POST',
        url: productURL,
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(data),
        dataType: "json",
        success: function () { SaveSuccess() },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(errorThrown); return;
        }
    });
}
